package com.example.controller;

import Getfdfeatures.Getfdfeatures;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.example.common.Result;
import com.example.constants.MATLABConstants;
import com.example.constants.PythonConstants;
import com.example.entity.Account;
import com.example.entity.LoginUser;
import com.example.entity.User;
import com.example.service.LoginService;
import com.example.service.NiiFileService;
import com.example.service.UserService;
import com.example.utils.JwtUtil;
import com.example.utils.RedisCache;
import com.example.utils.ScriptUtil;
import com.mathworks.toolbox.javabuilder.MWArray;
import com.mathworks.toolbox.javabuilder.MWNumericArray;
import org.jasypt.encryption.StringEncryptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

import java.util.Arrays;



@RestController
public class WebController {

    private static final Logger log = LoggerFactory.getLogger(WebController.class);
    @Autowired
    private UserService userService;

    @Autowired
   private AuthenticationManager authenticationManager;

    /**
     * 默认请求接口
     */
    @GetMapping("/")
    public Result hello() {
        return Result.success();
    }

    /**
     * 登录
     * @param account
     * @return
     */
   @PostMapping("/login")
    public Result login(@RequestBody Account account) {
        //AuthenticationManager authentication 进行用户认证
        try{
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(account.getUsername(),account.getPassword())
            );
            //认证成功则获取用户详情,生成jwt
           LoginUser loginUser = (LoginUser) authentication.getPrincipal();
            String userId = loginUser.getUser().getId().toString();
            String jwt = JwtUtil.createJWT(userId);
            Map<String,Object> map = new HashMap<>();
            map.put("token",jwt);
            map.put("user",loginUser);
            //将用户信息以键值对的方式存入redis
            redisCache.setCacheObject("login"+userId,loginUser);
            //如果认证通过了将jwt和user返回给前端
            return Result.success(map);
        }catch (Exception e){
            return Result.error(e.getMessage());
        }
    }

    /**
     * 注册
     */
    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        if (StrUtil.isBlank(user.getUsername()) || StrUtil.isBlank(user.getPassword())
                || ObjectUtil.isEmpty(user.getRole())) {
            return Result.error("参数输入异常");
        }
        userService.add(user);
        return Result.success();
    }

    /**
     * 退出登录从redis中删除用户信息
     * @return
     */
    @PostMapping("/userLogout")
    public Result logout(){
        //从SecurityContextHolder中获取用户id
        UsernamePasswordAuthenticationToken authenticationToken  = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authenticationToken.getPrincipal();
        //System.out.println(loginUser);
        String userId = loginUser.getUser().getId().toString();
        //删除redis中的值
        redisCache.deleteObject("login"+userId);
         return Result.success();
    }

    /**
     * 修改密码
     */
    @PutMapping("/updatePassword")
    public Result updatePassword(@RequestBody Account account) {
        userService.updatePassword(account);
        return Result.success();
    }

    /**
     * 加密接口
     * @return
     */
    @Autowired
    private StringEncryptor encryptor;

    @GetMapping("/Encryptor")
    public Result Enc(String source) {
        String target = encryptor.encrypt(source);
        return Result.success(target);
    }

    @Autowired
    NiiFileService niiFileService;
    /**
     * 测试接口
     * @return
     */
    @RequestMapping("/test")
    public Result test() {
        try {
            log.info("模型拟合");
            Getfdfeatures features = new Getfdfeatures();
            features.runfdfeatures(MATLABConstants.TARGET_DIR, MATLABConstants.ROIL_TARGER_DIR, MATLABConstants.ROIR_TARGET_DIR);
            log.info("拟合完成");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.success("测试成功！！");
    }

    /**
     * 测试redis接口
     */
    @Autowired
    private RedisCache redisCache;

    @GetMapping("/redis")
    public Result redis() {
        redisCache.setCacheObject("test","redis测试信息");
        return Result.success("已成功保存");
    }
}
